import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:yinshui_caiying/widgets/picker/models/ad_list_result_model.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

typedef AdCallback(List<AdItemModel> currentList);
typedef AllCallback(dynamic data);

class AdPickerContentView extends StatefulWidget {
  AdPickerContentView(
      {required this.data,
      required this.selectData,
      required this.onConfirm,
      this.onAll,
      this.title,
      this.showTitleBar = true});
  final String? title;
  final List<AdItemModel> data;
  final int? selectData;
  final AdCallback onConfirm;
  final AllCallback? onAll;
  final bool showTitleBar;
  @override
  State<StatefulWidget> createState() => AdPickerState(
      this.data,
      this.selectData,
      this.onConfirm,
      this.onAll,
      this.title,
      this.showTitleBar);
}

class AdPickerState extends State<AdPickerContentView> {
  AllCallback? _onAll;
  AdCallback _onConfirm;
  String? _title;
  bool _showTitleBar;

  ///选中的数据
  int? _selectData = 1;

  ///多级数据列存储的列表
  List<List<AdItemModel>> _dataList = [];

  ///正确存放数据列表
  List<AdItemModel> _currentList = [];

  ///原始树结构数据
  List<AdItemModel> _data = [];

  ///存储选中的每一列的index
  List<int>? _selectIndexList = [];

  ///滚动控制器的集合
  List<FixedExtentScrollController> _scrollCtrlList = [];

  AdPickerState(this._data, this._selectData, this._onConfirm, this._onAll,
      this._title, this._showTitleBar) {
    _init();
  }
  _init() {
    ///1.记录各级选中的index，并求取列表长度给出初始默认值
    if (_selectData != null && _selectData != 0) {
      ///当传入的数据有值时，递归遍历树结构的源数据，记录节点inex，得出类似[0,1,12,105]的结构
      _selectIndexList = findPathByLeafId(_selectData!, _data, null);
    } else {
      ///当无值时，采用另外一个递归方法，目的是为了求取树的深度,得出类似[0,0,0]深度为3的结构
      _selectIndexList = findPath(_data, null);
    }

    ///这个时候，我们把对应的数据全部放好,并且把控制器集合也创建好
    for (var i = 0; i < _selectIndexList!.length; i++) {
      int index = _selectIndexList![i];

      ///放入控制器集合，有几个放几个并且对应的位置也初始化好
      _scrollCtrlList.add(FixedExtentScrollController(initialItem: index));

      ///首先得放第一层,

      if (i == 0) {
        ///第一级就是他本身，后续的级别根据_selectIndexList[i]的index值去放
        ///1,增加第一级数据源
        _dataList.add(_data);
      }
      if (_dataList[i][index].children != null &&
          _dataList[i][index].children!.length > 0) {
        ///只要本级对应正确的项目有子集就把这一级添加到_dataList里去

        _dataList.add(_dataList[i][index].children!);
      }
    }

    ///上面一步已经整理好了多级的数据列表，下面一步就是整理正确的数据列表
    for (var i = 0; i < _selectIndexList!.length; i++) {
      int index = _selectIndexList![i];
      _currentList.add(_dataList[i][index]);
    }

    ///正确的数据列表页整理完毕
  }

  ///递归树形结构数据源-有对应值时
  ///
  ///[leafId]对应的数据id
  ///
  ///[nodes]原始树结构数据，注意类型
  ///
  ///[path] 供递归使用，最后返回记录正确节点的数组列表，类似[1,5,23,102]
  List<int>? findPathByLeafId(
      int leafId, List<AdItemModel> nodes, List<int>? path) {
    if (path == null) {
      path = [];
    }
    for (var i = 0; i < nodes.length; i++) {
      List<int> tmpPath = [];
      tmpPath.addAll(path);
      tmpPath.add(i);
      if (leafId == nodes[i].id) {
        return tmpPath;
      }
      if (nodes[i].children != null && nodes[i].children!.length > 0) {
        var findResult = findPathByLeafId(leafId, nodes[i].children!, tmpPath);
        if (findResult != null) {
          return findResult;
        }
      }
    }
  }

  ///递归树形结构数据源-无对应值时
  ///
  ///[nodes]原始树结构数据，注意类型
  ///
  ///[path] 供递归使用，最后返回记录0的节点的数组列表，类似[0,0,0]
  ///
  ///这个方法主要是为了求取树节点的深度
  List<int>? findPath(List<AdItemModel> nodes, List<int>? path) {
    if (path == null) {
      path = [];
    }
    for (var i = 0; i < nodes.length; i++) {
      List<int> tmpPath = [];
      tmpPath.addAll(path);
      tmpPath.add(0);
      if (nodes[i].children == null || nodes[i].children!.length == 0) {
        return tmpPath;
      }
      if (nodes[i].children!.length > 0) {
        var findResult = findPath(nodes[i].children!, tmpPath);
        if (findResult != null) {
          return findResult;
        }
      }
    }
  }

  @override
  void dispose() {
    ///组件销毁时注销所有的滚动控制器
    _scrollCtrlList.forEach((element) {
      element.dispose();
    });
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.end,
      children: [_renderPickerView()],
    );
  }

  ///列表变动时重新对应到值
  ///
  ///[index] 该列表的索引
  ///
  ///[num]数据列表的索引
  void _setItem(index, num) {
    for (var i = 0; i < _dataList.length; i++) {
      if (num == i) {
        ///先把正确的列表替换了
        _currentList[num] = _dataList[num][index];
        // _scrollCtrlList[num].jumpToItem(index);
        if (_dataList[num][index].children != null &&
            _dataList[num][index].children!.length > 0) {
          setState(() {
            _dataList[num + 1] = _dataList[num][index].children!;
          });
        }
      }
      if (i > num) {
        _currentList[i] = _dataList[i][0];
        _scrollCtrlList[i].jumpToItem(0);
        if (_dataList[i][0].children != null &&
            _dataList[i][0].children!.length > 0) {
          setState(() {
            _dataList[i + 1] = _dataList[i][0].children!;
          });
        }
      }
    }
  }

  double _pickerFontSize(String text) {
    // double ratio = hasTown ? 0.0.sp : 2.0.sp;
    // if (text == null || text.length <= 6) {
    //   return 38.0.sp;
    // } else if (text.length < 9) {
    //   return 36.0.sp + ratio;
    // } else if (text.length < 13) {
    //   return 32.0.sp + ratio;
    // } else {
    //   return 30.0.sp + ratio;
    // }

    return 37.sp;
  }

  Widget _renderPickerView() {
    Widget itemView = _renderItemView();

    if (!_showTitleBar) {
      return itemView;
    }
    List<Widget> viewList = <Widget>[];
    if (_showTitleBar) {
      viewList.add(_titleView());
    }
    // if (_pickerStyle!.menu != null) {
    //   viewList.add(_pickerStyle!.menu);
    // }
    viewList.add(itemView);

    return Column(children: viewList);
  }

  Widget _renderItemView() {
    List<Widget> list = [];
    for (var i = 0; i < _dataList.length; i++) {
      list.add(Expanded(
        child: Container(
          padding: EdgeInsets.all(10.w),
          child: CupertinoPicker.builder(
            scrollController: _scrollCtrlList[i],
            itemExtent: 90.h,
            onSelectedItemChanged: (int index) {
              _setItem(index, i);
            },
            childCount: _dataList[i].length,
            itemBuilder: (_, index) {
              String text = _dataList[i][index].name;
              return Align(
                  alignment: Alignment.center,
                  child: Text(text,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: Colors.black87,
                          fontSize: _pickerFontSize(text)),
                      textAlign: TextAlign.start));
            },
          ),
        ),
      ));
    }

    return Container(
      height: 500.h,
      color: Colors.white,
      child: Row(children: list),
    );
  }

  // 选择器上面的view
  Widget _titleView() {
    Widget title() {
      if (_title != null) {
        return Text(
          _title!,
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 45.sp),
        );
      }
      if (_onAll != null) {
        return InkWell(
            onTap: () {
              _onAll!(null);

              Get.back();
            },
            child: Container(
              alignment: Alignment.center,
              child: Text('全部',
                  style: TextStyle(color: Colors.black, fontSize: 45.sp)),
            ));
      }
      return Text('');
    }

    return Container(
      height: 90.h,
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(30.w), topRight: Radius.circular(30.w))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          /// 取消按钮
          InkWell(
              onTap: () {
                Get.back();
              },
              child: Container(
                alignment: Alignment.center,
                padding: EdgeInsets.only(left: 30.w),
                child: Text('取消',
                    style: TextStyle(color: Colors.black, fontSize: 45.0.sp)),
              )),

          /// 标题
          title(),

          InkWell(
              onTap: () {
                _onConfirm(_currentList);
                Get.back();
              },
              child: Container(
                alignment: Alignment.center,
                padding: EdgeInsets.only(right: 30.w),
                child: Text('确定',
                    style: TextStyle(color: Colors.black, fontSize: 45.sp)),
              ))

          /// 确认按钮
        ],
      ),
    );
  }
}
